//
//  BaseWebViewController.m
//  Elife
//
//  Created by 拓客营 on 2022/7/1.
//

#import "BaseWebViewController.h"
#import <WebKit/WebKit.h>

@interface BaseWebViewController ()<WKUIDelegate,WKNavigationDelegate>

@property(nonatomic,strong)UIProgressView *progressView;
@property(nonatomic,strong)WKWebView *webView;

@property (nonatomic, copy) NSString *htmlStr;
@property (nonatomic, copy) NSString *webUrlStr;

@property (nonatomic, copy) NSString *requestUrl;// 通过请求获取html字符串

@end

@implementation BaseWebViewController

#pragma mark - LifeCycle
- (instancetype)initWithTitle:(NSString *)navTitle htmlStr:(NSString *)htmlStr {
    if (self = [super init]) {
        self.navigationItem.title = navTitle;
        self.htmlStr = htmlStr;
    }
    return self;
}

- (instancetype)initWithTitle:(NSString *)navTitle requestUrl:(NSString *)url {
    if (self = [super init]) {
        self.navigationItem.title = navTitle;
        self.requestUrl = url;
    }
    return self;
}

- (instancetype)initWithUrlStr:(NSString *)urlStr {
    if (self = [super init]) {
        self.webUrlStr = urlStr;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self UIConfig];
    
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self.navigationController.navigationBar setHidden:NO];
    [self.navigationController.navigationBar navBarAlpha:1 isOpaque:NO];
}


- (void)dealloc {
    NSLog(@"WK已被移除");
//    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
    [self.webView removeObserver:self forKeyPath:@"title"];
}

#pragma mark - view layout
-(void)UIConfig {
    
//    //进度条初始化
//    self.progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 2)];
//    self.progressView.backgroundColor = [UIColor blueColor];
//    //设置进度条的高度，下面这句代码表示进度条的宽度变为原来的1倍，高度变为原来的1.5倍.
//    self.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.5f);
//    [self.view addSubview:self.progressView];

    // 1.创建webview，并设置大小，
    self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, NavigationBarHeight+2, ScreenWidth, ScreenHeight-NavigationBarHeight-2)];
    self.webView.backgroundColor = [UIColor clearColor];
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate = self;
    
    if ([self.webUrlStr isNotBlank]) {
        // 加载网页
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrlStr]]];

    }else if ([self.requestUrl isNotBlank]){
        [self getRichTextWithUrl:self.requestUrl];
    }else{
        // 加载本地
        [self reloadWebview:self.htmlStr];
    }
    
    // 将webView添加到界面
    [self.view addSubview:self.webView];
    
//    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
    [self.webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];// 监听webview的title
}

#pragma mark - Event Response
// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context {
    if ([keyPath isEqualToString:@"estimatedProgress"]) {
        self.progressView.progress = self.webView.estimatedProgress;
        if (self.progressView.progress == 1) {
            /*
             *添加一个简单的动画，将progressView的Height变为1.4倍，在开始加载网页的代理中会恢复为1.5倍
             *动画时长0.25s，延时0.3s后开始动画
             *动画结束后将progressView隐藏
             */
//            __weak typeof (self)weakSelf = self;
            WeakSelf
            [UIView animateWithDuration:0.25f delay:0.3f options:UIViewAnimationOptionCurveEaseOut animations:^{
                weakSelf.progressView.transform = CGAffineTransformMakeScale(1.0f, 1.4f);
            } completion:^(BOOL finished) {
                weakSelf.progressView.hidden = YES;
            }];
        }
    }else if ([keyPath isEqualToString:@"title"]) {
        if (object == self.webView) {
            self.navigationItem.title = self.webView.title;
        }else {
            [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
        }
    }else{
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}

#pragma mark - Delegate,DataSource
#pragma mark 网页开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    
}
#pragma mark 网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
}
// 1 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
     NSLog(@"%@", navigationAction.request.URL);
    NSLog(@"1-------在发送请求之前，决定是否跳转  -->%@",navigationAction.request);
    
    decisionHandler(WKNavigationActionPolicyAllow);
}
// 3 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
    /// 在收到服务器的响应头，根据response相关信息，决定是否跳转。decisionHandler必须调用，来决定是否跳转，参数WKNavigationActionPolicyCancel取消跳转，WKNavigationActionPolicyAllow允许跳转
    
    NSLog(@"3-------在收到响应后，决定是否跳转");
    
    decisionHandler(WKNavigationResponsePolicyAllow);
}
-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures
{
    NSLog(@"createWebViewWithConfiguration");
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark - Network
-(void)getRichTextWithUrl:(NSString *)url {
    WeakSelf;
    [MBProgressHUD showLoadingMessage:nil view:self.view];
    [[APIManager manager] Get:url parameters:nil success:^(id  _Nonnull responseObject) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        if (NET_RESULT_CODE == 1) {
            NSString *htmlStr = FormatString(@"%@",responseObject[@"data"][@"html"][@"html"]);
            [weakSelf reloadWebview:htmlStr];
        }else {
            NET_SHOW_MSG;
        }
    } failure:^(NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:weakSelf.view];
        NET_SHOW_ERROR;
    }];
}

#pragma mark - Method
- (void)reloadWebview:(NSString *)html{

    NSString *headerString = @"<header><meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=no'></header>";
       
    
    NSString *strCssHead = [NSString stringWithFormat:@"<head>"
                            "<link rel=\"stylesheet\" type=\"text/css\" href=\"webContent.css\">"
                            "</head>"];
    
//    [self.webView loadHTMLString:html baseURL:nil];
    [self.webView loadHTMLString:[NSString stringWithFormat:@"%@%@",[headerString stringByAppendingString:[NSString htmlEntityDecode:html]],strCssHead] baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"webContent" ofType:@"css"]]];
}


#pragma mark - Set Get


#pragma mark - Lazy

@end
